package com.cays.myresearch.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.cays.myresearch.MainActivity;
import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.activity.ClassActivity;
import com.cays.myresearch.activity.ClassInfoActivity;
import com.cays.myresearch.adapter.ClassItemsAdapter;
import com.cays.myresearch.adapter.ClassesAdapter;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.ClassItems;
import com.cays.myresearch.entity.Classes;
import com.cays.myresearch.entity.ResponseInfo;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by lenovo on 2018/6/23.
 */

public class ClassesFragment extends BaseFragment
        implements ClassItemsAdapter.ClassItemClickListener, ClassesAdapter.ClassesClickListener{
    private View view;
    private List<ClassItems> classesItemLists=new ArrayList<>();
    private List<Classes> classesLists=new ArrayList<Classes>();
    private ClassItemsAdapter classItemsAdapter;
    private PtrFrameLayout ptrFrameLayout;
    private ClassesAdapter infoAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(view==null){
            view=inflater.inflate(R.layout.classes_layout,container,false);
        }
        initClasses();
        initRefresh();
        return view;
    }
    private void initClasses(){
        classesItemLists.clear();
        classesLists.clear();
        ClassItems []classes={new ClassItems("科研工具",R.drawable.c3),new ClassItems("论文写作",R.drawable.c3)
        ,new ClassItems("办公软件",R.drawable.c3),new ClassItems("智能算法",R.drawable.c3)};
        for(int i=0;i<classes.length;i++)classesItemLists.add(classes[i]);
        //item
        GridLayoutManager layoutManager=new GridLayoutManager(getActivity(),4);
        RecyclerView recyclerView=(RecyclerView)view.findViewById(R.id.classes_class_list1);
        recyclerView.setLayoutManager(layoutManager);
        classItemsAdapter=new ClassItemsAdapter(classesItemLists);
        recyclerView.setAdapter(classItemsAdapter);
        classItemsAdapter.setClassItemClickListener(this);
        //list
        RecyclerView recyclerView1=(RecyclerView)view.findViewById(R.id.classes_info_list);
        infoAdapter=new ClassesAdapter(classesLists);
        GridLayoutManager layoutManager1=new GridLayoutManager(getActivity(),1);
        recyclerView1.setLayoutManager(layoutManager1);
        recyclerView1.setAdapter(infoAdapter);
        infoAdapter.setmClassesListener(this);
        ptrFrameLayout=(PtrFrameLayout)view.findViewById(R.id.classes_refresh);
    }
    public void initRefresh(){
        //这里是一个自定义的头部刷新布局,自带的也有一个布局   new PtrDefaultHandler();
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(getActivity());
        ptrFrameLayout.addPtrUIHandler(header);
        //不仅仅是添加头布局,还需要设置到控件中 注:特别重要,不然没显示
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                //执行调用下拉刷新监听
                ptrFrameLayout.autoRefresh(true);
            }
        },100);
        //设置下拉刷新监听
        ptrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //在这里写自己下拉刷新数据的请求
                //需要结束刷新头
                refreshClasses();
                //ptrFrameLayout.refreshComplete();
            }
        });
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:infoAdapter.notifyDataSetChanged();break;
                default:break;
            }
            ptrFrameLayout.refreshComplete();
            super.handleMessage(msg);
        }
    };
    private void refreshClasses(){
        final String url= Constant.URL+"class/list";
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendHttpRequest(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        classesLists.clear();
                        Message message=new Message();
                        message.what=1;handler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String s=response.body().string(),info="",classes="";
                        if (s.contains("~")) {
                            info=s.split("~")[0];
                            classes=s.split("~")[1];
                            List<Classes> classList=Constant.gson.fromJson(classes,
                                    new TypeToken<List<Classes>>(){}.getType());
                            classesLists.clear();
                            if(!classList.isEmpty())classesLists.addAll(classList);
                        }
                        Message message=new Message();
                        message.what=1;handler.sendMessage(message);
                    }
                });
            }
        }).start();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        MainActivity.currTag= Constant.fragment_classes;
    }

    @Override
    public void classItemClick(int position) {
        Intent intent=new Intent(getActivity(), ClassActivity.class);
        intent.putExtra("classType","");
        startActivity(intent);
    }

    @Override
    public void onClassesClick(int position) {
        Classes info=classesLists.get(position);
        Intent intent=new Intent(getActivity(), ClassInfoActivity.class);
        intent.putExtra("intent_class",Constant.gson.toJson(info));
        startActivity(intent);
    }
}
